import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '../components/Component'
import { connect } from 'react-redux'
import { message, List, Skeleton, Button, Radio, Checkbox, Space, Modal, Input, Badge } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import moment from 'moment'
import style from './MessageList.module.less'
import { updateUncompleteMessage } from '../redux/actions'
import { confirmAction, strToNum } from '@src/assets/js/tool'
const { Item } = List
const { confirm } = Modal
const { Search } = Input
class MessageList extends Component {
  state = {
    list: [],
    loading: false,
    messageTypes: [{ title: '全部消息', c: 0 }],
    messageType: '全部消息',
    type: '未处理',
    searchText: '',
    pagination: {
      current: 1,
      pageSize: 20,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: total => `共 ${total} 条记录`,
      size: 'small'
    },
    checkedList: [],
    onlyAutoDeal: false
  }

  // 获取消息列表
  getTableData () {
    const { pagination, type, onlyAutoDeal, messageType, searchText } = this.state
    const { current, pageSize } = pagination
    const condition = []
    const form = {
      current,
      page_size: pageSize,
      auto_action: onlyAutoDeal ? 1 : 0
    }
    if (type === '未处理') {
      condition.push({ k: 'complete_datetime', o: 'null' })
    } else {
      condition.push({ k: 'complete_datetime', o: 'not null' })
    }
    if (messageType !== '全部消息') {
      condition.push({ k: 'title', o: '=', v: messageType })
    }
    if (searchText) {
      condition.push({ k: 'content', o: 'like', v: `%${searchText.trim()}%` })
    }
    form.condition = JSON.stringify(condition)
    this.setState({ loading: true })
    this.$get('/api/xapc/message', form).then(res => {
      this.setState({ loading: false })
      if (res.status === 1) {
        this.setState({
          list: res.data.list,
          checkedList: [],
          pagination: {
            ...pagination,
            total: res.data.total
          }
        })
      } else {
        return message.warning(res.message)
      }
    }).catch(() => this.setState({ loading: false }))
  }

  toDealHandle (d) {
    let route = d.route ? d.route : null
    if (!route) {
      return message.warning('处理地址不存在')
    }
    try {
      route = JSON.parse(route)
    } catch (e) {
      return message.warning('获取处理地址错误')
    }
    const component = route.component || route.type
    if (component === 'caseDetail') {
      const { id, operate } = route.meta
      this.props.addWindow({ id: `CaseDetail-${id}`, title: `案件详情-${route.title}`, componentName: 'CaseDetail', forceRefresh: false, meta: { id, operate, editable: true } })
    }
    this.setMessageReaded(d.id)
  }

  // 设置未读信息未已读
  setMessageReaded (id) {
    this.$put(`/api/xapc/message/read/${id}`)
      .then(res => {
        if (res.status === 1) {
          this.props.updateUncompleteMessage()
          this.getTableData()
        } else {
          message.warning(res.message)
        }
      })
  }

  // 设置未读信息未已读
  setRead (id) {
    const h = message.loading('提交中', 120)
    this.$put('/api/xapc/message/makeRead', { id })
      .then(res => {
        h()
        if (res.status === 1) {
          this.props.updateUncompleteMessage()
          this.getMessageTypes()
          this.getTableData()
        } else {
          message.warning(res.message)
        }
      }, () => h())
  }

  // 改变已处理和未处理类型
  changeType (e) {
    this.setState({
      type: e.target.value,
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData()
      this.getMessageTypes()
    })
  }

  // 表格请求变化
  listChange (current, pageSize) {
    this.setState({
      pagination: {
        ...this.state.pagination,
        current,
        pageSize
      }
    }, () => {
      this.getTableData()
    })
  }

  // 全选操作
  checkAll () {
    const messages = this.state.list.filter(li => li.auto_action)
    const list = this.state.checkedList
    if (list.length !== messages.length) {
      this.setState({
        checkedList: messages.map(li => li.id)
      })
    } else {
      this.setState({
        checkedList: []
      })
    }
  }

  // 勾选消息
  checkItem (id) {
    const list = this.state.checkedList.slice()
    const index = list.indexOf(id)
    if (index === -1) {
      list.push(id)
    } else {
      list.splice(index, 1)
    }
    this.setState({
      checkedList: list
    })
  }

  // 批量处理二次确认
  multiDealConfirm () {
    confirm({
      icon: <ExclamationCircleOutlined />,
      content: '您确定要批量处理吗',
      onOk: () => {
        this.multiDealRequest()
      }
    })
  }

  // 批量处理请求
  multiDealRequest () {
    const hide = message.loading('处理中', 120)
    this.$post('/api/xapc/message/autoAction', {
      ids: this.state.checkedList.join()
    }).then(res => {
      hide()
      if (res.status === 1) {
        message.success('处理成功')
        this.getTableData()
      } else {
        message.warning(res.message)
      }
    }).catch(() => hide())
  }

  // 获取消息类型
  getMessageTypes () {
    const hide = message.loading('获取消息类型', 120)
    const condition = []
    if (this.state.type === '未处理') {
      condition.push({ k: 'complete_datetime', o: 'null' })
    }
    return this.$get('/api/xapc/message/getType', {
      condition: JSON.stringify(condition)
    })
      .then(res => {
        hide()
        if (res.status === 1) {
          const types = res.data || []
          const t = types.reduce((a, b) => { return { c: strToNum(a.c) + strToNum(b.c) } })
          types.unshift({ title: '全部消息', c: t.c })
          this.setState({
            messageTypes: types
          })
        } else {
          message.warning(res.message)
        }
      }).catch(() => hide())
  }

  // 改变消息类型
  changeMessageType (t) {
    this.setState({
      messageType: t,
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData()
    })
  }

  formatDate (t) {
    if (!t) {
      return null
    }
    return moment(t * 1000).format('YYYY-MM-DD HH:mm')
  }

  onSearch (s) {
    this.setState({
      searchText: s,
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData()
    })
  }

  componentDidMount () {
    this.getMessageTypes()
    this.getTableData()
  }

  renderUnreadTag (time, needDo) {
    if (!time) {
      return (
        <span className={style['undeal-tag']}>（{needDo === 1 ? '未处理' : '未查看'}）</span>
      )
    }
  }

  // 渲染消息类型选择器
  renderTypes () {
    return this.state.messageTypes.map((li, i) => {
      const className = [style['title-cell']]
      if (this.state.messageType === li.title) {
        className.push(style.active)
      }
      return (
        <Badge key={i} count={li.c} offset={[-16, 16]}>
          <div className={className.join(' ')} onClick={() => this.changeMessageType(li.title)}>
            <span>{li.title}</span>
          </div>
        </Badge>
      )
    })
  }

  render () {
    const { loading, list, pagination, checkedList } = this.state
    pagination.onChange = this.listChange.bind(this)
    const optionalList = list.filter(li => li.auto_action)
    const checkedAll = checkedList.length === optionalList.length && checkedList.length
    const allCheckDisable = optionalList.length === 0
    const indeterminate = !checkedAll && checkedList.length
    const unChecked = checkedList.length === 0
    return (
      <div className={style.container}>
        <div className={style['title-line']}>
          <div className={style['title-list']}>
            {this.renderTypes()}
          </div>
        </div>
        <div className={style['message-list']}>
          <div className={style['message-type']}>
            <span className={style['total-deal']}>
              <Space size='middle'>
                <Checkbox checked={checkedAll} indeterminate={indeterminate} disabled={allCheckDisable} onChange={() => this.checkAll()} />
                <Button disabled={unChecked || allCheckDisable} type='primary' onClick={() => this.multiDealConfirm()}>批量处理</Button>
              </Space>
            </span>
            <Space>
              <Checkbox checked={this.state.onlyAutoDeal} onChange={v => this.setState({ onlyAutoDeal: v.target.checked }, () => this.getTableData())}>只显示可批量</Checkbox>
              <Radio.Group value={this.state.type} onChange={e => this.changeType(e)}>
                <Radio.Button value='未处理'>未处理</Radio.Button>
                <Radio.Button value='已处理'>已处理</Radio.Button>
              </Radio.Group>
              <Search placeholder='请输入' onSearch={s => this.onSearch(s)} allowClear />
            </Space>
          </div>
          <List
            loading={loading}
            itemLayout='horizontal'
            dataSource={list}
            pagination={pagination}
            renderItem={(item, i) => {
              const checked = this.state.checkedList.indexOf(item.id) !== -1
              return (
                <Item
                  className={style['message-line']} actions={[
                    <Button
                      type='link' key='read' onClick={() => confirmAction(`请确认 “${i + 1}、${item.title}” 是否已处理完毕？确认后，该消息将不在提醒！`, () => {
                        this.setRead(item.id)
                      })}
                    >已读
                    </Button>,
                    <Button type='link' key='deal' onClick={() => this.toDealHandle(item)}>{item.complete_datetime ? '查看' : (item.need_do === 1 ? '处理' : '查看')}</Button>
                  ]}
                >
                  <Skeleton avatar title={false} loading={item.loading} active>
                    <Item.Meta
                      title={(
                        <Space size='middle'>
                          {item.auto_action ? <Checkbox checked={checked} onChange={() => this.checkItem(item.id)} /> : null}
                          <span>{i + 1}、{item.title}{this.renderUnreadTag(item.complete_datetime, item.need_do)}</span>
                          <span className={style.date}>{this.formatDate(item.create_datetime)}</span>
                          {item.level ? <span className={style.urgency}>紧急</span> : null}
                        </Space>
                      )}
                      description={item.content}
                    />
                  </Skeleton>
                </Item>
              )
            }}
          />
        </div>
      </div>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
    updateUncompleteMessage: () => dispatch(updateUncompleteMessage(dispatch))
  }
})

export default connect(mapState, mapDispatch)(MessageList)
